package com.cch.android.activity.view;

 
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cch.android.activity.PuzzleImageActivity;
import com.cch.android.activity.R;
import com.cch.android.activity.adapter.ImageListAdapter;
import com.cch.android.util.MyLog;

public class ImageFolderListActivity extends Activity implements View.OnClickListener {  
	
	private GridView gridView;
	
	public TextView countText;
	
	public static int maxCount = 0;
	
	public static int displayWidth, displayHeight; 
	
	private ImageListAdapter cursorAdapter;
	
	private Cursor imageCursor; 
	
	private Context context; 
	
	private String filePath;	// 当前文件夹目录

	private Button btn_upload,btn_cancel;
	
	private ImageView selectView;
	//当前选择位置
	public int select_position=-1;

	//上一次位置
	private ArrayList<String> selectImagePaths = new ArrayList<String>();	//选择上传的所有图片
	private int mPosition=0 ;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		setContentView(R.layout.folder_imagelist);
		filePath = getIntent().getExtras().getString("filePath");
		
		if (dialog == null) {
			dialog = ProgressDialog.show(this, "", getString(R.string.loading), true); 
			dialog.setCancelable(true);
		}
		initView(); 
		setAdapter();
		// 跳转到图片选择界面
		gridView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				
				if(maxCount<4){
				imageCursor.moveToPosition(position);
				int nTemp = imageCursor.getColumnIndex("_data");
				String imagePath = imageCursor.getString(nTemp);
				View views = gridView.getChildAt(position);
				selectView = (ImageView)views.findViewById(R.id.selectImageView);
				try {
				if(selectView.getVisibility()==View.GONE){ 
						selectImagePaths.add(imagePath);
						selectView.setVisibility(View.VISIBLE);
						maxCount++;
				
				}else{
					selectView.setVisibility(View.GONE);
					if(selectImagePaths!=null && selectImagePaths.size()>0)
					selectImagePaths.remove(imagePath);
					maxCount--;
				}
				}catch (OutOfMemoryError e) {
					e.printStackTrace();
				} catch (IndexOutOfBoundsException e) { e.printStackTrace();
				} catch (Exception e) { e.printStackTrace();
				}
				MyLog.log("选择图片数量："+selectImagePaths.size());
				MyLog.log("选择图片路径："+imagePath);
			}else{
				//提示超过四张图片
				Toast toast = Toast.makeText(getApplicationContext(),
					     "最多只能选择四张图片", Toast.LENGTH_LONG);
					   toast.setGravity(Gravity.CENTER, 0, 0);
					   toast.show();
			}
			}
		});
		
	
	}
	private void initView(){
		gridView = (GridView)findViewById(R.id.gridView);
		btn_upload = (Button)findViewById(R.id.btn_ok);
		btn_cancel = (Button)findViewById(R.id.btn_cancel);
		btn_cancel.setOnClickListener(this);
		btn_upload.setOnClickListener(this); 
	}
	private ProgressDialog dialog=null;

	private void setAdapter() {
		if (imageCursor != null && !imageCursor.isClosed()) {
			imageCursor.close();
		}
		imageCursor = getCursor();
		if (imageCursor != null && imageCursor.getCount() > 0) {
			
			List<Bitmap> dataSource =new ArrayList<Bitmap>();
			
			BitmapFactory.Options options = new BitmapFactory.Options();
			options.inSampleSize = 100;
			
			cursorAdapter = new ImageListAdapter(context, imageCursor);
			gridView.setAdapter(cursorAdapter);

//			for(imageCursor.moveToFirst(); !imageCursor.isAfterLast();imageCursor.moveToNext()) {
//				int id = imageCursor.getInt(imageCursor.getColumnIndex("_ID"));
//				Bitmap bitmap = MediaStore.Images.Thumbnails.getThumbnail(context.getContentResolver(), id,
//						MediaStore.Images.Thumbnails.MICRO_KIND, options);
//				cursorAdapter.setNotifyDataSetChanged(bitmap);
//			}
//			
			if (dialog != null || dialog.isShowing())
				dialog.dismiss();
		}
	}

	private int computeInitialSampleSize(BitmapFactory.Options options, int minSideLength, int maxNumOfPixels) {
		double w = options.outWidth;
		double h = options.outHeight;
		int lowerBound = (maxNumOfPixels == -1) ? 1 : (int) Math.ceil(Math.sqrt(w * h / maxNumOfPixels));
		int upperBound = (minSideLength == -1) ? 128 : (int) Math.min(Math.floor(w / minSideLength), Math.floor(h
				/ minSideLength));
		if (upperBound < lowerBound) {
			return lowerBound;
		}
		if ((maxNumOfPixels == -1) && (minSideLength == -1)) {
			return 1;
		} else if (minSideLength == -1) {
			return lowerBound;
		} else {
			return upperBound;
		}
	}

	private Cursor getCursor() {
		Uri originalUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		ContentResolver cr = context.getContentResolver();
		// "_id DESC"的作用是使新拍摄的照片可以在前面显示
		imageCursor = cr.query(originalUri, null, "_data like '%" + filePath + "%'", null, "_id DESC");
		String[] strings = imageCursor.getColumnNames();
//		for (int i = 0; i < strings.length; i++) {
//			MyLog.debug(getClass(), "YYYYYYYYYYYYYYYYYYYYY:"+strings[i]);
//		}
		return imageCursor;
	} 
	
	private void backNitiveManagerActivity(){
		if (gridView != null) {
			gridView.setVisibility(View.GONE);
			gridView = null;
		}
		if (imageCursor != null && !imageCursor.isClosed()) {
			imageCursor.close();
		}
		setResult(RESULT_OK);
		finish();
	}
	 
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
				backNitiveManagerActivity(); 
				return true;
		}
		return super.onKeyDown(keyCode, event);
	} 
	 
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		new Thread(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				if(cursorAdapter!=null)
					cursorAdapter.clearDataSource();
			}
		}.start();
		maxCount =0;
		if(selectImagePaths!=null)selectImagePaths.clear();
		
		super.onDestroy();
		
	} 
	
	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_ok: 
			Intent intentChoose = new Intent();
			intentChoose.putExtra("chooseimagelist", selectImagePaths);
			intentChoose.setClass(this, PuzzleImageActivity.class);
			startActivity(intentChoose);
			finish();
			break;
		case R.id.btn_cancel:
			backNitiveManagerActivity();
			break;	
		default:
			break;
		}
	}
	
    int mSingleChoiceID = -1;
    
	 public void DisplayToast(String str)  
	    {  
	        Toast toast=Toast.makeText(this, str, Toast.LENGTH_LONG);  
	        toast.setGravity(Gravity.TOP,0,220);  
	        toast.show();  
	    } 
	 
	private final int UPLOADING=1;
}
